<?php

class AdminWidgetsController extends AppController
{
    public $helpers = array('Html', 'Form');

    public $components = array(
        'RequestHandler',
        'Session',
        'Auth' => array(
            'loginRedirect' => array('controller' => 'Home', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'Home', 'action' => 'display', 'index')
        )
    );
    var $uses = array(
        'Page',
        'Category',
        'WidgetType',
        'Widget'
    );

    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->loginAction = array('plugin' => 'users', 'controller' => 'users', 'action' => 'login', 'admin' => false);
        $this->Auth->loginRedirect = '/';
        $this->Auth->logoutRedirect = '/';
        $this->Auth->authError = __('Sorry, but you need to login to access this location.', true);
        $this->Auth->loginError = __('Invalid e-mail / password
		combination.  Please try again', true);
        $this->Auth->autoRedirect = true;
        $this->Auth->userModel = 'User';
        $this->Auth->userScope = array('User.active' => 1, 'User.is_admin' => '1');
        if ($this->Auth->user()) {
            $this->set('userData', $this->Auth->user());
            $this->set('isAuthorized', ($this->Auth->user('id') != ''));
        }
        $this->layout = 'admin';
    }

    public function index()
    {
        $this->set('pages', $this->Page->find('all'));
    }

    public function view($id = null)
    {
        if (!$id) {
            throw new NotFoundException(__('Invalid page'));
        }

        $page = $this->Page->findById($id);
        if (!$page) {
            throw new NotFoundException(__('Invalid page'));
        }
        $this->set('page', $page);
    }

    public function listTypes()
    {
        $widgets = $this->WidgetType->find('all');
        $this->set('widgets', $widgets);
        $this->layout = false;
    }

    public function add()
    {
        //set whatever data is required to build the page;
        //be sure this is done before instantiating the View class so all
        //set variables are passed when you pass this controller object in the constructor
        $this->layout = false;
        $this->autoRender = false;
		
		// Load widget thirdparty components
		$widgetName = $this->request->is('post') ? $this->request->data['widget'] : $this->request->query['widget'];
		$this->{ucfirst($widgetName) . 'Init'} = $this->Components->load(ucfirst($widgetName).'Widget.'.ucfirst($widgetName).'Init');
		foreach($this->{ucfirst($widgetName) . 'Init'}->components as $component)
			$this->{preg_split('/\./', $component)[1]} = $this->Components->load($component);

		$view = new View($this); 
		foreach($this->{ucfirst($widgetName) . 'Init'}->components as $helper)
			$view->loadHelper($helper);
		
        if ($this->request->is('post')) {
            $widgetName = $this->request->data['widget'];
			
            $this->Widget->create();

            $pageId = $this->request->data['id_page'];
            $grid = $this->request->data['grid'];

            $this->request->data['Widget']['name'] = $widgetName;
            $this->request->data['Widget']['value'] = $this->{ucfirst($widgetName) . 'Init'}->getValue($this->request->data['value']);
            if ($this->Widget->save($this->request->data)) {
                $page = $this->Page->findById($pageId);
                $stdGrid = json_decode($grid, true);
                $stdGrid[count($stdGrid) - 1]['id_widget'] = $this->Widget->id;

                $page['Page']['grid'] = json_encode($stdGrid);
                $this->Page->save($page);

                $view->set('widget', $this->request->data['Widget']);
				$html = $view->render(ucfirst($widgetName) . 'Widget.Crud/view', null);
                return json_encode(array('id' => $this->Widget->id, 'html' => $html));
            }
        }

        return json_encode(array('html' => $view->render(ucfirst($widgetName) . 'Widget.Crud/add', null)));
    }

    public function edit()
    {
        //set whatever data is required to build the page;
        //be sure this is done before instantiating the View class so all
        //set variables are passed when you pass this controller object in the constructor
        $this->layout = false;
        $this->autoRender = false;
		$view = new View($this); 

        if ($this->request->is('post')) {
            $widgetName = $this->request->data['widget'];
            $widgetId = $this->request->data['id_widget'];

            $pageId = $this->request->data['id_page'];
            $grid = $this->request->data['grid'];
            $this->request->data['Widget']['id'] = $widgetId;
            $this->request->data['Widget']['name'] = $widgetName;

            $this->{ucfirst($widgetName) . 'Init'} = $this->Components->load(ucfirst($widgetName).'Widget.'.ucfirst($widgetName).'Init');
            $this->request->data['Widget']['value'] = $this->{ucfirst($widgetName) . 'Init'}->getValue($this->request->data['value']);

            if ($this->Widget->save($this->request->data)) {
                $page = $this->Page->findById($pageId);
                $page['Page']['grid'] = $grid;
                $this->Page->save($page);

                $view->set('widget', $this->request->data['Widget']);
                $html = $view->render(ucfirst($widgetName) . 'Widget.Crud/view', null);
            }

            return json_encode(array('id' => $this->Widget->id, 'html' => $html));
        }

        $widgetName = $this->request->query['widget'];
        $widgetId = $this->request->query['id_widget'];
        $widget = $this->Widget->findById($widgetId);
        $this->request->data = $widget;
        $this->render(ucfirst($widgetName) . 'Widget.Crud/edit');
    }

    public function delete()
    {
		$this->autoRender = false;
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }
        if ($this->Widget->delete($this->request->data['id_widget'])) {
			return 'OK';
        }
    }

    public function getSubCat()
    {
        $id_cat = $this->request->data('id_cat');
        if (!$id_cat) {
            throw new NotFoundException(__('Invalid category'));
        }

        $category = $this->Category->findById($id_cat);
        if (!$category) {
            throw new NotFoundException(__('Invalid category'));
        }
        $subcats = $category['Children'];
        $this->set('subcats', $subcats);
        $this->set('_serialize', array('subcats'));
    }

}

?>